package main

import (
	"html/template"
	"log"
	"path/filepath"
	"simple-crm/config"
	"simple-crm/middleware"
	"simple-crm/routes"
	"simple-crm/utils"
	"strings"

	"github.com/gin-contrib/multitemplate"
	"github.com/gin-contrib/sessions"
	"github.com/gin-contrib/sessions/cookie"
	"github.com/gin-gonic/gin"
)

func main() {
	// 加载配置
	cfg := config.Load()

	// 初始化数据库
	db := config.InitDB(cfg)

	// 设置Gin模式
	if cfg.App.Mode == "production" {
		gin.SetMode(gin.ReleaseMode)
	}

	// 创建Gin引擎
	r := gin.Default()
	r.Use(middleware.CORSMiddleware())

	// 配置session中间件
	store := cookie.NewStore([]byte(cfg.App.SessionSecret))

	r.Use(sessions.Sessions("simple-crm-session", store))

	// Load templates explicitly
	r.HTMLRender = loadTemplates("./templates")

	// 注册路由
	routes.SetupRoutes(r, db, cfg)

	// 启动服务器
	log.Printf("服务器启动在端口: %s", cfg.App.Port)
	if err := r.Run(":" + cfg.App.Port); err != nil {
		log.Fatal("启动服务器失败:", err)
	}
}

func loadTemplates(templatesDir string) multitemplate.Renderer {
	r := multitemplate.NewRenderer()

	// 设置模板函数
	funcMap := template.FuncMap{
		"hasPermission":    utils.HasPermission,
		"hasAnyPermission": utils.HasAnyPermission,
		"substr":           utils.Substr,
		"eq":               utils.Eq,
		"contains":         utils.Contains,
	}

	layouts, err := filepath.Glob(templatesDir + "/layouts/*.html")
	if err != nil {
		panic(err.Error())
	}

	includes, err := filepath.Glob(templatesDir + "/**/*.html")
	if err != nil {
		panic(err.Error())
	}

	// Generate our templates map from our layouts/ and includes/ directories
	for _, include := range includes {

		filePath := filepath.Dir(include)
		if strings.Contains(filePath, "layout") {
			continue
		}

		layoutCopy := make([]string, len(layouts))
		if strings.Contains(filePath, "auth") {
			// Auth templates don't need base layout, they are standalone
			layoutCopy = []string{include}
		} else {
			copy(layoutCopy, layouts)
			layoutCopy = append(layoutCopy, include)
		}

		tagname := strings.Replace(include, "templates/", "", 1)
		log.Printf("加载模板: %s", tagname)
		log.Printf("加载模板: %v", layoutCopy)

		r.AddFromFilesFuncs(tagname, funcMap, layoutCopy...)
	}
	return r
}
